import React, { useEffect, useState } from 'react'
import { Form, Button, Input, Modal, Select, Row, Col, TreeSelect, Descriptions, Card } from 'antd'
import { channelList, probationDayList, jobLevelTypeList, socialTraineeStateArray ,reinstateList, employeeStatusList,websiteList } from '@/utils/constant'
import { isNewOrReinstate, getJobByOrgId } from '../../service'
import { findItemByTree } from '@/utils/functions'

import moment from 'moment'
import { connect } from 'umi'

const FormItem = Form.Item
const { Option } = Select

const formLayout = {
  labelCol: { span: 7 },
}

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
}

const CreateForm = (props) => {

  const { onSubmit, onCancel, currentUser, personnel = {}, current } = props
  const { options = {} } = personnel
  const { orgTree = [], orgLine = [], orgSystem = [], jobLevel = [] } = options

  const [form] = Form.useForm()
  const [formVals, setFormVals] = useState({
    socialTrainee: '0',
    principal: currentUser.name,
    id: props.values.id,
  })

  const [unitTree, setUnitTree] = useState([])
  const [jobList, setJobList] = useState([])
  const [jobSelectLevel, setJobSelectLevel] = useState(jobLevel)
  const [oldInfo, setOldInfo] = useState({})
  const [oid,setOid] = useState()
  const [loading,setLoading] = useState()

  useEffect(() => {
    if (current) {
      form.setFieldsValue(current)
      setOid(current.oid)
      const item = findItemByTree(orgTree, current.orgId)
      setUnitTree(item ? item.children : [])
      current.unitId && getJobByOrgId(current.unitId).then((res) => {
        setJobList(res)
      })
      if (current.jobLevelType === '2') {
        setJobSelectLevel(jobLevel.filter(e => e.type === 'CODE_MANAGEMENTRANK'))
      } else if (current.jobLevelType === '1') {
        setJobSelectLevel(jobLevel.filter(e => e.type === 'CODE_PROFESSIONALRANK'))
      }
      if(current.isReinstate !==0) {
        //非新员工
        isNewOrReinstate(current.idcard).then((res)=>{
          setOldInfo(res)
        })
      }
    }
  }, [current])

  const onFormCancel = () => {
    form.resetFields()
    onCancel()
    setOldInfo(null)
  }

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields()
    setFormVals({ ...formVals, ...fieldsValue })
    form.resetFields()
    onSubmit({...fieldsValue,oid:oid})
    setOldInfo(null)
  }

  const onChangeUnitId = (e) => {
    getJobByOrgId(e).then((res) => {
      setJobList(res)
    })
  }

  const onChangeOrgId = (e) => {
    const item = findItemByTree(orgTree, e)
    setUnitTree(item ? item.children : [])
  }

  const filterOption = (input, option) => {
    return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  }

  const onChangeJobLevelType = (e) => {
    if (e == 2) {
      setJobSelectLevel(jobLevel.filter(e => e.type === 'CODE_MANAGEMENTRANK'))
    } else {
      setJobSelectLevel(jobLevel.filter(e => e.type === 'CODE_PROFESSIONALRANK'))
    }
  }

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="principal" label="招聘负责人">
              <Input/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="orgId" label="公司">
              <TreeSelect treeData={orgTree} onChange={onChangeOrgId}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="unitId" label="部门">
              <TreeSelect treeData={unitTree} onChange={onChangeUnitId}/>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="jobId" label="职位">
              <Select placeholder="请选择" showSearch filterOption={filterOption}>
                {jobList.map((item, index) => {
                  return (
                    <Option value={`${item.coidassignedjob}`} key={item.coidassignedjob}>
                      {item.cname}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="workAddress" label="工作地点">
              <Input/>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="name" label="姓名">
              <Input/>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="privatemail" label="个人电子邮箱">
              <Input/>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="mobile" label="手机">
              <Input/>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="idcard" label="身份证">
              <Input/>
            </FormItem>
          </Col>

          {/*<Col {...colStyle}>*/}
          {/*  <FormItem name="hiredate" label="拟入职日期">*/}
          {/*    <DatePicker/>*/}
          {/*  </FormItem>*/}
          {/*</Col>*/}

          <Col {...colStyle}>
            <Form.Item name="jobLevelType" label="职级类型">
              <Select placeholder="请选择" showSearch filterOption={filterOption} onChange={onChangeJobLevelType}>
                {jobLevelTypeList.map((item, index) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </Form.Item>
          </Col>

          <Col {...colStyle}>
            <Form.Item name="jobLevelId" label="职级">
              <Select placeholder="请选择" showSearch filterOption={filterOption}>
                {
                  jobSelectLevel.map((item, index) => {
                    return (
                      <Option value={`${item.id}`} key={item.id}>
                        {item.name}
                      </Option>
                    )
                  })
                }
              </Select>
            </Form.Item>
          </Col>

          <Col {...colStyle}>
            <FormItem name="socialTrainee" label="招聘类型">
              <Select placeholder="请选择">
                {socialTraineeStateArray.map((item, index) => {
                  return (
                    <Option value={`${index}`} key={index}>
                      {item}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="channel" label="招聘渠道">
              <Select placeholder="请选择" showSearch filterOption={filterOption}>
                {
                  channelList.map((item, index) => {
                    return (
                      <Option value={`${item.value}`} key={item.value}>
                        {item.label}
                      </Option>
                    )
                  })
                }
              </Select>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="personnelWeb" label="招聘网站">
              <Select placeholder="请选择" showSearch filterOption={filterOption}>
                {
                  websiteList.map((item, index) => {
                    return (
                      <Option value={item.value} key={item.value}>
                        {item.label}
                      </Option>
                    )
                  })
                }
              </Select>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="innerReferrer" label="推荐人（内部）">
              <Input/>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="outerReferrer" label="推荐人（外部）">
              <Input/>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="probationday" label="试用期">
              <Select placeholder="请选择" showSearch filterOption={filterOption} onChange={onChangeJobLevelType}>
                {probationDayList.map((item, index) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="monthlySalary" label="原单位固定月薪">
              <Input/>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="performance" label="原单位浮动绩效">
              <Input/>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="jobSystemId" label="体系">
              <Select placeholder="请选择" showSearch filterOption={filterOption}>
                {orgSystem.map((item, index) => {
                  return (
                    <Option value={`${item.id}`} key={item.id}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>

          <Col {...colStyle}>
            <FormItem name="lineId" label="条线">
              <Select placeholder="请选择" showSearch filterOption={filterOption}>
                {orgLine.map((item, index) => {
                  return (
                    <Option value={`${item.id}`} key={item.id}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
        </Row>
        {
          oldInfo && oldInfo.name &&  <Card
            title="复职员工原信息"
            bordered={false}
          >
            <Descriptions >
              <Descriptions.Item label="原公司名称">{oldInfo.orgname}</Descriptions.Item>
              <Descriptions.Item label="原部门名称">{oldInfo.unitname}</Descriptions.Item>
              <Descriptions.Item label="原岗位名称">{oldInfo.jobname}</Descriptions.Item>
              <Descriptions.Item label="原工号">{oldInfo.code}</Descriptions.Item>
              <Descriptions.Item label="员工状态">{employeeStatusList.find(e=>oldInfo.employeestatus===e.value)?.label}</Descriptions.Item>
              <Descriptions.Item label="招聘类型">{reinstateList.find(e=>oldInfo.type===e.value)?.label}</Descriptions.Item>
              <Descriptions.Item label="原入职日期">{oldInfo.oldhiredate && moment(oldInfo.oldhiredate).format('YYYY-MM-DD')}</Descriptions.Item>
              <Descriptions.Item label="原离职日期">{oldInfo.dimissiondate && moment(oldInfo.dimissiondate).format('YYYY-MM-DD')}</Descriptions.Item>
              <Descriptions.Item label="是否中心负责人">{oldInfo.iscentreprincipal===0 ? '是' : '否'}</Descriptions.Item>
              <Descriptions.Item label="是否部门负责人">{oldInfo.isdepartmentprincipa===0 ? '是' : '否'}</Descriptions.Item>
            </Descriptions>
          </Card>
        }
      </>
    )
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleSubmit()}>发起录用流程</Button>
      </>
    )
  }

  return (
    <Modal
      width={1280}
      destroyOnClose
      title="发起录用"
      visible={!!current}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        initialValues={{ ...formVals }}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}


export default connect(({ user, personnel }) => ({
  personnel,
  currentUser: user.currentUser,
}))(CreateForm)
